package com.higgins.eventtracking.server;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class WeatherService {
	private String urlText = "http://www.accuweather.com/en/gb/tonbridge/tn9-1/hourly-weather-forecast/323734";
	private BufferedReader in = null;
	private String firstLabel = "<tr class=\"forecast\">";
	private String startElement = "<div class=";
	private String stopElement = "</div>";
	private String elementSubString = "\">";
    private List<Integer> cloudCover;
    private String firstCloudCoverLabel = "<th scope=\"row\">Cloud Cover</th>";
    private String startCloudCoverElement = "<td class=";
    private String stopCloudCoverElement = "%</td>";
    private String elementSubCloudCoverString = "\">";
    private Integer cloudCoverThreshold = 30;
	
	public WeatherService()	{
	}
	public String checkForSun()	{
		List<String> listOfWeather = getHourlyWeather();
		Calendar cal = Calendar.getInstance();
		int hourNow = cal.get(Calendar.HOUR_OF_DAY);
		Integer timeOfSun = getTimeOfSun(listOfWeather, hourNow);
		Integer timeSunEnds = getTimeSunEnds(listOfWeather, hourNow, timeOfSun);
		if (timeOfSun!=null)	{
			String returnString = null;
			if (timeOfSun.equals(hourNow))	{
				returnString = "Sunny now!!!!";
			} else {
				returnString = "Sun Starts at " + timeOfSun + ":00 hours!";
			}			
			if (timeSunEnds!=null && returnString != null)	{
				returnString = returnString + "; until " + timeSunEnds + ":00 hours!";
			}
			return returnString;
		}
		return null;
	}
	public Integer getTimeOfSun(List<String> listOfWeather, int hourNow)	{
	    int count = 0;
		for (String weather:listOfWeather)	{
		    try   {
    		    if (cloudCover.get(count) <= cloudCoverThreshold)  {
                    return hourNow;
    		    }
		    } catch (Exception e) {
		        
		    }
			if (weather.equals("Partly Cloudy"))	{
				return hourNow;
			}
			if (weather.equals("Partly Sunny"))	{
				return hourNow;
			}
			if (weather.equals("Sunny"))	{
				return hourNow;
			}
			if (weather.equals("Mostly Sunny"))	{
				return hourNow;
			}
			if (weather.equals("Mostly Clear"))	{
				return hourNow;
			}
			hourNow++;
			count++;
		}
		return null;
	}
	public Integer getTimeSunEnds(List<String> listOfWeather, Integer hourNow, Integer timeOfSun)	{
	    int count = 0;
		for (String weather:listOfWeather)	{
			if (timeOfSun != null && hourNow != null && hourNow > timeOfSun)	{
			    try  {
    			    if (cloudCover.get(count) > cloudCoverThreshold)  {
                        return (hourNow + 1) > 23? (hourNow + 1 - 24):(hourNow + 1);
    			    }
			    } catch (Exception e)    {
			        
			    }
				if (!weather.equals("Partly Cloudy") && !weather.equals("Partly Sunny") && 
						!weather.equals("Sunny") && !weather.equals("Mostly Sunny") && 
						!weather.equals("Mostly Clear"))	{
					return (hourNow + 1) > 23? (hourNow + 1 - 24):(hourNow + 1);
				}
			}
			hourNow++;
			count++;
		}
		return null;
	}
	public List<String> getHourlyWeather()	{
		List<String> weatherList = new ArrayList<String>();
		URL url;
		try {
			url = new URL(urlText);
	        URLConnection yc = url.openConnection();
	        in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
	        String inputLine = in.readLine();
	        while (!inputLine.contains(firstLabel) && inputLine!=null)	{
		        inputLine = in.readLine();
			}
			inputLine = inputLine.substring(inputLine.indexOf(firstLabel) + firstLabel.length());
	        while (inputLine!=null && !inputLine.contains("</tr>") && !inputLine.contains("<tr class=\"temp\">"))	{
	        	inputLine = in.readLine();
		        while (!inputLine.contains(startElement) && inputLine!=null && !inputLine.contains("</tr>"))	{
			        inputLine = in.readLine();
				}
	        	if (!inputLine.contains("</tr>") && !inputLine.contains("<tr class=\"temp\">") && inputLine!=null)	{
			        inputLine = inputLine.substring(inputLine.indexOf(startElement) + startElement.length());
			        int elementSubStringDigit = inputLine.indexOf(elementSubString);
			        int stopElementDigit = inputLine.indexOf(stopElement);
			        String weather = inputLine.substring(elementSubStringDigit+2, stopElementDigit);
			        weatherList.add(weather);
	        	}
			}
	        
		} catch (Exception e) {

		}
		checkForCloudCover();
		return weatherList;
	}
	
    public void checkForCloudCover()  {
        cloudCover = new ArrayList<Integer>();
        try {
            String inputLine = in.readLine();
            while (!inputLine.contains(firstCloudCoverLabel) && inputLine!=null)  {
                inputLine = in.readLine();
            }
            inputLine = inputLine.substring(inputLine.indexOf(firstCloudCoverLabel) + firstCloudCoverLabel.length());
            while (inputLine!=null && !inputLine.contains("</tr>") && !inputLine.contains("<tr class=\"temp\">"))   {
                inputLine = in.readLine();
                while (!inputLine.contains(startCloudCoverElement) && inputLine!=null && !inputLine.contains("</tr>"))    {
                    inputLine = in.readLine();
                }
                if (!inputLine.contains("</tr>") && !inputLine.contains("<tr class=\"temp\">") && inputLine!=null)  {
                    inputLine = inputLine.substring(inputLine.indexOf(startCloudCoverElement) + startCloudCoverElement.length());
                    int elementSubStringDigit = inputLine.indexOf(elementSubCloudCoverString);
                    int stopElementDigit = inputLine.indexOf(stopCloudCoverElement);
                    String cloudCoverStr = inputLine.substring(elementSubStringDigit+2, stopElementDigit);
                    try {
                        Integer cloudCoverValue = Integer.valueOf(cloudCoverStr);
                        cloudCover.add(cloudCoverValue);
                    } catch (Exception e)   {
                        cloudCover.add(100);
                    }
                }
            }
            
        } catch (Exception e) {

        }
    }	
	
}
